var api = require('./../../../config/api.js');
var app = getApp();
var util = require('./../../../utils/util.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    runTypeList: ["代买", "代取/送"],
    runIndex: 0,
    runText: '请选择',
    expressText: "请选择", // 选择的快递公司
    expressList: ['其它'], // 快递公司下拉框
    expressId: 99,
    expressIdList: [],
    sizeText: "请选择", // 型号内容
    sizeList: ["小", "中", "大"], // 型号下拉框
    showChooseTime: false, // 是否选择定时达
    timeText: "请选择", // 填写的时间
    dateText: "请选择", // 填写的日期
    showConfirm: false,
    takeType: [
      { name: 'common', value: '普通', checked: true },
      { name: 'urgent', value: '加急' },
    ],
    takeValue: "common",
    addressLoad: false, // 是否加载了地址
    takeAddress: { // 配送地址信息
      takeAddressId: 0,
      takeAddress: "",
      takeSchool: ""
    },
    takeList: [],
    takeIdList: [],
    getAddress: {
      "aaId": 0,
      "uId": "",
      "aaName": "",
      "aaSex": 1,
      "aaMobile": "",
      "csId": 0,
      "csName": "",
      "ssId": 0,
      "ssName": "",
      "aaAddress": "",
      "aaDefault": 0,
      "createTime": ""
    }, // 配送地址信息
    payMoney: 5, // 支付最小金额
    payMin: 5, // 允许最小支付
    smsText: "", // 填写的快递短信
    memoText: "", // 备注
    payInfo: {},
    orderType: 'takeOut',
    buyModel: 'common',  // 是否加急
    goodsText: '', //购买物品
    timeNum: -1, // 当前服务器时间段
    isRun: 1, // 是否服务
    timeToastText: '',
    isNow: false,
    morePrice: 2,
    urgentPrice: 0,
    urgentTimes: 2,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    console.log(options);

    var configUrl = api.PriceConfig + '/' + app.globalData.userInfo.addition.uCustomInfo.csId + '/takeout';
    util.myRequest(configUrl, false, function (data) {
      for (var i = 0; i < data.data.length; i++){
        if (data.data[i].cpProperty == 'common'){
          that.setData({ payMoney: parseInt(data.data[i].cpPrice), payMin: data.data[i].cpPrice});
        } else if (data.data[i].cpProperty == 'more'){
          that.setData({ morePrice: data.data[i].cpPrice});
        } else if (data.data[i].cpProperty == 'urgentTimes') {
          that.setData({ urgentTimes: data.data[i].cpPrice});
        }
      }
    });

    var tail = ''
    if (JSON.stringify(options) != '{}') {
      tail = '/' + options.aaId;
    }
    var url = api.CreateOrderInfo + '/' + app.globalData.userInfo.token + tail + '/' + that.data.orderType;
    util.myRequest(url, false, function (data) {
      var info = data.data;

      if (Array.isArray(info.receiveAddressInfo)) {
        // 无地址跳转到添加地址
        that.addReceiveAddress();
        return;
      }

      that.setData({
        expressList: info.expressInfo.nameList,
        expressIdList: info.expressInfo.idList,
        sizeList: info.packageSize,
        takeList: info.takeAddressList.nameList,
        takeIdList: info.takeAddressList.idList,
        // takeAddress: info.takeAddressList,
        getAddress: info.receiveAddressInfo,
        timeNum: info.timeNum,
        timeToastText: info.timeToastText,
        addressLoad: true,
      });

      if (info.timeNum == 1 || info.timeNum == 5 ){
        that.setData({isRun: false})
      }

      var takeAddress = {};
      var takeList = info.takeAddressList;
      takeAddress.takeAddressId = takeList.idList[0];
      takeAddress.takeAddress = takeList.nameList[0].split(' ')[1];
      takeAddress.takeSchool = takeList.nameList[0].split(' ')[0];

      that.setData({ takeAddress: takeAddress });
      that.getExpress(takeList.idList[0]);
    });

    if (app.globalData.userInfo.isSubscribe == 0) {
      wx.showToast({
        title: '亲，关注校运通公众号，骑士接单后会有微信通知哦!',
        icon: 'none',
        duration: 3000,
        mask: false,
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return app.globalData.shareInfo;
  },

  getExpress: function (stId) {
    return;
    var that = this;
    util.myRequest(api.TakeExpress + '/' + stId, false, function (data) {
      that.setData({
        expressList: data.data.nameList,
        expressIdList: data.data.idList,
      });
    });
  },

  /**
   * 获取默认金额
   */
  getDefaultPay: function () {
    var that = this;
    if (this.data.getAddress.ssId != 0 && this.data.takeAddress.takeAddressId != 0 && this.data.sizeText != '请选择') {
      var ssId = this.data.getAddress.ssId;
      var stId = this.data.takeAddress.takeAddressId;
      var size = this.data.sizeText;

      var url = api.DefaultPay + '/' + stId + '/' + ssId + '/' + size;
      util.myRequest(url, false, function (data) {
        var payMoney = data.data;
        var coefficient = 1;
        if (that.data.takeValue == 'urgent') {
          coefficient = 2;
        } else if (that.data.takeValue == 'clock') {
          coefficient = 1.5
        } else if (that.data.takeValue == 'urgentClock') {
          coefficient = 1.5 * 2
        }
        that.setData({
          payMoney: payMoney * coefficient,
          payMin: payMoney * coefficient,
        });
      });
    }
  },

  /**
   * 选择跑腿服务类型
   */
  runTypeChange: function (e) {
    var that = this;
    console.log(e.detail)
    console.log('picker发送选择改变，携带值为', e.detail.value)
    that.setData({
      runIndex: e.detail.value,
      runText: that.data.runTypeList[e.detail.value]
    })

    this.getDefaultPay();
  },

  /**
   * 选择地址
   */
  expressChange: function (e) {
    var that = this;
    console.log(e.detail)
    console.log('picker发送选择改变，携带值为', e.detail.value)
    that.setData({
      expressText: that.data.expressList[e.detail.value],
      expressId: that.data.expressIdList[e.detail.value],
    })

    this.getDefaultPay();
  },

  /**
   * 关闭地址
   */
  closeExpress: function () {
    var that = this;
    that.setData({ chooseExpress: false });
  },

  /**
   * 选择取货地址列表
   */
  takeListChange: function (e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    var takeAddress = {};
    var takeIdList = this.data.takeIdList;
    var takeList = this.data.takeList;
    takeAddress.takeAddressId = takeIdList[e.detail.value];
    takeAddress.takeAddress = takeList[e.detail.value].split(' ')[1];
    takeAddress.takeSchool = takeList[e.detail.value].split(' ')[0];
    this.setData({ takeAddress: takeAddress });

    this.getDefaultPay();

    this.getExpress(takeIdList[e.detail.value]);
  },

  /**
   * 选择快递大小
   */
  sizeChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    console.log(e)
    this.setData({
      sizeText: this.data.sizeList[e.detail.value]
    })

    this.getDefaultPay();
  },

  /**
   * 选择日期
   */
  dateChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      dateText: e.detail.value
    })
  },

  /**
   * 选择时间
   */
  timeChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      timeText: e.detail.value
    })
  },

  /**
   * 选择送快递时间方式
   */
  takeTypeChange: function (e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    if (e.detail.value == 'urgent') {
      this.setData({ showChooseTime: false });
    } else if (e.detail.value == 'clock') {
      this.setData({ showChooseTime: true });
    } else if (e.detail.value == 'common') {
      this.setData({ showChooseTime: false });
    } else if (e.detail.value == 'urgentClock') {
      this.setData({ showChooseTime: true });
    }
    this.setData({ takeValue: e.detail.value });

    this.getDefaultPay();
  },

  /**
   * 添加取货地址
   */
  addGetAddress: function () {
    console.log('addGetAddress')
    var that = this;
    wx.redirectTo({
      url: './../../address/list/list?orderType=' + that.data.orderType + '&do=get'
    })
  },

  /**
   * 添加送达地址
   */
  addReceiveAddress: function () {
    console.log('addReceiveAddress')
    var that = this;
    // wx.navigateTo({
    wx.redirectTo({
      url: './../../address/list/list?orderType=' + that.data.orderType + '&do=send'
    })
  },

  /**
   * 跳转收货列表
   */
  goAddressList: function () {
    console.log('goAddressList')
    var that = this;
    // wx.navigateTo({
    wx.redirectTo({
      url: './../../address/list/list?orderType=' + that.data.orderType + '&do=takeOut'
    })
  },

  checkboxChange: function (e) {
    console.log('checkbox发生change事件，携带value值为：', e.detail.value)

    var payMin = this.data.payMin;
    var urgentPrice = this.data.urgentPrice;
    var urgentTimes = this.data.urgentTimes;
    var payMoney = this.data.payMoney;
    var morePrice = this.data.morePrice;
    if (e.detail.value.length > 0){
      this.setData({ 
        isNow: true, 
        takeValue: 'urgent',
        payMin: payMin * urgentTimes,
        payMoney: payMoney * urgentTimes,
        morePrice: morePrice * urgentTimes,
      })
    }else{
      this.setData({ 
        isNow: false,
        takeValue: 'common',
        payMin: payMin / urgentTimes,
        payMoney: payMoney / urgentTimes,
        morePrice: morePrice / urgentTimes,
      })
    }
  },

  /**
   * 支付金额
   */
  payInput: function (e) {
    var that = this;
    if (e.detail < this.data.payMin) {
      this.setData({
        payMoney: that.data.payMoney
      })
    } else {
      this.setData({
        payMoney: e.detail
      })
    }

  },

  goodsInput: function(e){
    this.setData({
      goodsText: e.detail.value
    })
  },

  /**
   * 快递短信
   */
  smsInput: function (e) {
    this.setData({
      smsText: e.detail.value
    })
  },

  /**
   * 订单备注
   */
  memoInput: function (e) {
    this.setData({
      memoText: e.detail.value
    })
  },

  /**
   * 下单
   */
  doOrder: function (e) {
    var that = this;

    var aoTakeInfo = that.data.goodsText;
    if (aoTakeInfo == ""){
      wx.showToast({
        title: '请填写外卖信息',
        icon: 'none',
        duration: 2000
      })
      return;
    }

    var postData = {
      token: app.globalData.userInfo.token,
      aaId: that.data.getAddress.aaId,
      csId: that.data.getAddress.csId,
      aoLevel: that.data.takeValue,
      aoPay: that.data.payMoney,
      aoSmsCopy: that.data.smsText,
      aoMemo: that.data.memoText,
      aoTakeInfo: that.data.goodsText,
      aoType: 'takeout',
    };

    util.myRequest(api.AddOrder, postData, function (data) {
      that.setData({ payInfo: data.data });
      that.wxPay();
    });
  },

  wxPay: function () {
    var that = this;
    var showDuration = 2000;
    wx.requestPayment({
      'timeStamp': that.data.payInfo.timeStamp,
      'nonceStr': that.data.payInfo.nonceStr,
      'package': that.data.payInfo.package,
      'signType': 'MD5',
      'paySign': that.data.payInfo.paySign,
      'success': function (res) {
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: showDuration
        })

        setTimeout(function () {
          wx.redirectTo({
            url: './../order/order'
          })
        }, showDuration);
      },
      'fail': function (res) {
        wx.showToast({
          title: '支付失败',
          icon: 'success',
          duration: showDuration
        })

        setTimeout(function () {
          wx.navigateBack({
            delta: 1
          })
        }, showDuration);
      }
    })
  }
})